package com.lizhaoshan.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.lizhaoshan.annotation.EmployeeLoginToken;
import com.lizhaoshan.annotation.PassToken;
import com.lizhaoshan.common.CodeMsg;
import com.lizhaoshan.common.Result;
import com.lizhaoshan.common.TokenHolder;
import com.lizhaoshan.constant.TokenConstant;
import com.lizhaoshan.dto.EmployeeDto;
import com.lizhaoshan.pojo.Employee;
import com.lizhaoshan.pojo.PageBean;
import com.lizhaoshan.service.EmployeeService;
import com.lizhaoshan.service.TokenService;
import com.lizhaoshan.utils.TokenUtil;
import com.lizhaoshan.vo.EmployeeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @program: reggie
 * @description:
 * @author: lamour
 * @create: 2022-05-14 19:54
 **/
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 登录验证
     * @param employeeDto
     * @return
     */
    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    public Result<Object> login(@RequestBody EmployeeDto employeeDto) {
        log.info("********员工登录中");
        employeeDto.setPassword(DigestUtils.md5DigestAsHex(employeeDto.getPassword().getBytes()));
        log.info("********用户名和密码验证");
        Employee employee = employeeService.selectByCondition(employeeDto);

        if(Objects.isNull(employee)){
            return Result.error("用户名或密码错误");
        }

        String token = TokenUtil.createToken(employee.getUsername(), employee.getId());
        log.info("**********将token作为key，员工信息作为value存入redis缓存中");

        EmployeeDto newEmployeeDto = new EmployeeDto();
        BeanUtils.copyProperties(employee, newEmployeeDto);
        redisTemplate.opsForValue().set(TokenConstant.EMPLOYEE_TOKEN_PREFIX+token, JSON.toJSONString(newEmployeeDto),2L, TimeUnit.HOURS);

        EmployeeVo employeeVo = new EmployeeVo();

        employeeVo.setToken(token);
        BeanUtils.copyProperties(newEmployeeDto, employeeVo);

        log.info("********员工成功登录");
        return Result.success(employeeVo);
    }


    @PostMapping(value = "/logout")
    @PassToken
    public Result<String> logout() {
        //不理解为什么移除id后就能退出
        TokenHolder.removeCurrentId();

        log.info("员工成功登出");
        return Result.success("成功退出");
    }

    @PostMapping
    public Result addEmployee(@RequestBody EmployeeDto employeeDto){
        log.info("********添加员工***** begin");
        boolean insertEmployee = employeeService.insertEmployee(employeeDto);
        log.info("********添加员工***** end");
        return insertEmployee ? Result.success("添加员工成功") : Result.error("添加员工失败");
    }

    @PutMapping
    public Result putEmployee(@RequestBody EmployeeDto employeeDto){
        log.info("********修改员工***** begin");
        boolean updateEmployee = employeeService.updateEmployee(employeeDto);
        log.info("********修改员工***** end");
        return updateEmployee ? Result.success("修改员工成功") : Result.error("修改员工失败");
    }

    @GetMapping("/page")
    public Result getPages(@RequestParam(value = "name", required = false) String name,
                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        log.info("**********员工分页查询，begin");
        PageBean<EmployeeVo> employeePageBean = employeeService.selectPage(page, pageSize, name);
        log.info("**********员工分页查询，end");

        return Objects.nonNull(employeePageBean) ? Result.success(employeePageBean) : Result.error("员工分页查询失败");
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable String id){
        log.info("**********员工分页查询，begin");
        Employee employee = employeeService.selectById(id);
        log.info("**********员工分页查询，end");

        return Objects.isNull(employee) ? Result.success("员工分页查询成功") : Result.error("员工分页查询失败");
    }


}
